<?php

namespace pos\services\order;

use pos\extensions\ApiBaseService;

use common\services\order\OrderCommonService;
use common\models\mall\MallCartModel;
use pos\services\active\ActivePromotionService;
use pos\services\active\ActiveCouponService;
use pos\services\user\UserService;
use common\tools\Util;
use common\models\order\OrderModel;
use common\models\order\OrderGoodsModel;

use common\models\goods\goods\GoodsModel;
use common\models\active\ActiveCouponReceiveModel;
use common\models\user\UserModel;



/**
 * Desc 订单管理服务类
 * @author WMX
 */
class OrderService extends ApiBaseService
{
    /**
     * 订单提交
     * @param array $params 请求参数
     * * */
    public static function submit($params)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $headers = \Yii::$app->getRequest()->getHeaders();
            $device = $headers->get('deviceId');
            if (empty($device)) {
                throw new \Exception('收银机号异常');
            }
            $user = []; // 用户信息
            if (!empty($params['phone'])) {
                $user = UserModel::findOne(['phone' => $params['phone']]);
                if (empty($user)) {
                    // 执行注册逻辑——获取用户ID
                    $user = UserService::register($params);
                }
            }

            //商品信息
            $cart = MallCartModel::getAll(['device' => $device, 'state' => MallCartModel::STATE_ENABLE],  ['id', 'gid', 'count', 'state as select', 'price', 'spec', 'user_id', 'device']);

            if (empty($cart[0]['gid'])) {
                throw new \Exception('商品数据异常');
            }

            //活动信息——计算商品活动
            $activity = ActivePromotionService::calcGoodsAmount($cart);
            if (empty($activity['list'])) {
                throw new \Exception('商品活动信息异常');
            }
            // 归类商品
            $goods = array_column($activity['list'], 'goods');

            $active_goods = [];
            // 合并商品信息
            foreach ($goods as $value) {
                $active_goods = array_merge($active_goods, $value);
            }

            //券处理
            if ($params['coupon_code']) {
                list($gs, $coupon_amount) = ActiveCouponService::couponCalculate($active_goods, $activity['payment_amount'], $params['coupon_code'], $user);
                $activity['coupon_amount'] = $coupon_amount;
                $activity['payment_amount'] = $activity['payment_amount'] -  $coupon_amount;
                $active_goods = $gs;
            }

            //创建订单
            $order = self::createOrder($activity, $device, $params, $user);
            //创建订单商品商品
            $goods = self::createOrderGoods($active_goods, $order, $params);

            //券更新
            if ($params['coupon_code'] && $activity['coupon_amount'] > 0) {
                ActiveCouponService::updateCouponState($params['coupon_code'], ActiveCouponReceiveModel::STATE_USE, $order['order_sn']);
            }
            $transaction->commit();
            //清空购物车
            if (!isset($cart[0]['cart'])) {
                MallCartModel::deleteAll(['device' => $device]);
            }
            return self::jsonSuccess([
                'order_sn' => $order['order_sn'],
                'payment_amount' => $activity['payment_amount'],
                'total_discount_amount' => $activity['coupon_amount'] + $activity['discount_amount']
            ]);
        } catch (\Exception $exc) {
            $transaction->rollBack();
            return self::jsonError($exc->getMessage());
        }
    }

    // 支付方式
    public static function payList()
    {
        return self::jsonSuccess([
            [
                'id' => 1,
                'name' => '微信'
            ],
            // [
            //     'id'=> 2,
            //     'name' => '支付宝'
            // ],
            [
                'id' => 3,
                'name' => '现金'
            ],
            [
                'id' => 4,
                'name' => '余额'
            ]
        ]);
    }

    /**
     * 订单创建
     * * */
    private static function createOrder($data, $device, $params, $user = [])
    {
        $order_sn = Util::createSn('wk');
        $params = [
            'user_id' => !empty($user) ? $user['id'] : '',
            'device' => $device,
            'type' => $params['type'],
            'order_sn' => $order_sn,
            'original_amount' => $data['total_amount'],
            'discount_amount' => $data['discount_amount'],
            'manjian_amount' => $data['manjian_amount'],
            'coupon_amount' => $data['coupon_amount'],
            'payment_amount' => $data['payment_amount'],
            'settlement_amount' => $data['payment_amount'],
            'order_time' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s'),
            'remark' => isset($params['reamrk']) ? $params['reamrk'] : '',
            'pickup_date' => empty($params['pickup_date']) ? date('Y-m-d H:i:s') : $params['pickup_date']
        ];
        $order = new OrderModel();
        $order->setAttributes($params, false);
        if (empty($order->save())) {
            throw new \Exception('订单创建异常');
        }
        return $order;
    }

    /**
     * 订单商品创建
     * * */
    private static function createOrderGoods($group_goods, $order, $params)
    {
        $pdata = [];
        foreach ($group_goods as $goods) {
            if ($goods['state'] != GoodsModel::STATE_LISTING) {
                throw new \Exception($goods['name'] . '已下架');
            }

            $pdata[] = [
                'order_sn' => $order['order_sn'],
                'gid' => $goods['gid'],
                'barcode' => $goods['barcode'],
                'name' => $goods['name'],
                'cate' => $goods['category'],
                'image' => $goods['thumb'],
                'spec' => $goods['spec'],
                'original_price' => $goods['price'],
                'price' => $goods['activity_price'],
                'settlement_price' => $goods['activity_price'],
                'count' => $goods['count'],
                'discount_price' => $goods['discount_amount'],
                'manjian_price' => $goods['manjian_amount'],
                'coupon_price' => $goods['coupon_amount'],
                'total_original_price' => $goods['amount'],
                'total_price' => round($goods['amount'] - $goods['discount_amount'] - $goods['manjian_amount'] - $goods['coupon_amount'], 2),
                'total_settlement_price' => round($goods['amount'] - $goods['discount_amount'] - $goods['manjian_amount'] - $goods['coupon_amount'], 2),
            ];

            // 更新商品销量
            GoodsModel::updateAllCounters(['sales' => $goods['count']], ['id' => $goods['id']]);
        }
        $res = \Yii::$app->db->createCommand()->batchInsert(OrderGoodsModel::tableName(), array_keys($pdata[0]), $pdata)->execute();
        if (empty($res)) {
            throw new \Exception('订单商品创建异常');
        }
        return $pdata;
    }

    /**
     * 列表——获取订单
     * @param array $params 参数 
     * **/
    public static function getList($params)
    {
        try {
            //检索条件
            $condition = ['AND'];
            if ($params['state']) {
                if ($params['state'] != 8) {
                    $condition[] = ['=', 'o.state', $params['state'] ?? ''];
                } else {
                    $condition[] = ['or', ['=', 'o.state', 2], ['=', 'o.state', 3], ['=', 'o.state', 1]];
                }
            }
            if ($params['pickup_no']) {
                $condition[] = ['=', 'o.pickup_no', $params['pickup_no'] ?? ''];
            }
            if ($params['order_sn']) {
                $condition[] = ['like', 'o.order_sn', $params['order_sn'] ?? ''];
            }
            $list = OrderCommonService::getUnionAll($condition, $params['page'], $params['page_size']);
            return self::jsonSuccess($list);
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }

    // 获取订单详情
    public static function getDetail($params)
    {
        try {
            $data = OrderCommonService::getOrderDetail($params['order_sn']);
            return self::jsonSuccess($data);
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }

    // 取消订单
    public static function cancel($params)
    {
        try {
            $res = OrderCommonService::cancel($params['order_sn']);
            if ($res == 'success') {
                return self::jsonSuccess([]);
            }
            return self::jsonError($res);
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }

    // 修改状态
    public static function send($params)
    {
        $data = OrderCommonService::getOrderDetail($params['order_sn']);
        if (empty($data)) {
            return self::jsonError('订单异常');
        }
        if (!($params['state'] == OrderModel::STATE_WAIT_DELIVERY || $params['state'] == OrderModel::STATE_WAIT_RECEIVE || $params['state'] == OrderModel::STATE_RECEIVED)) {
            return self::jsonError('状态异常');
        }
        $params['state'] = $params['state'];
        $condition = ['order_sn' => $params['order_sn']];
        unset($params['order_sn']);
        if (OrderModel::updateData($params, $condition) === false) {
            return self::jsonError('更新失败');
        }
        return self::jsonSuccess();
    }


    // 小票打印
    public static function printer($params)
    {
        try {
            $data = OrderCommonService::getOrderDetail($params['order_sn']);

            if (!empty($data)) {
                list($code, $msg) = OrderCommonService::printerOrder($data);
                if($code != 0) {
                    throw new \Exception('小票机异常：'.$msg);
                }
            }
            return self::jsonSuccess($data);
        } catch (\Exception $exc) {
            return self::jsonError($exc->getMessage());
        }
    }

    
}
